﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Collections.Concurrent;
using System.Threading;
using ClassLibraryMessageDataType;
using Newtonsoft.Json;
using ClassLibraryMessageDispacher;
namespace ClassLibrarySQLite
{

    public class SQLiteConnectionInfo
    {

        public SQLiteConnectionInfo(string ip)
        {
            this.ip = ip;
            this.connect = new SQLiteConnection();
        }

        public string steamcode
        {
            set;
            get;
        }
        public string ip
        { get; set; }

        public SQLiteConnection connect
        { set; get; }
    }
    /// <summary>
    /// 小型嵌入式数据库操作管理
    /// </summary>
    public sealed class ClassLibrarySQLiteMesManager
    {
        private List<SQLiteConnectionInfo> sqliteconnectionlist = new List<SQLiteConnectionInfo>();
         
        private static ConcurrentDictionary<string, ClassConnectionObj> connectionObjdic = new ConcurrentDictionary<string, ClassConnectionObj>();

        private static ConcurrentQueue<MessagePackage> mesQuenue = new ConcurrentQueue<MessagePackage>(); 
        private static Thread backTread;

        public ClassLibrarySQLiteMesManager()
        {
           
        }

        /// <summary>
        /// 
        /// </summary>
        public static void DBinit()
        {
            backTread = new Thread(back_sqlite_thread);
            backTread.Priority = ThreadPriority.Normal;
            backTread.IsBackground = true;
            backTread.Start();
        }

        public static void  PushMessageIntoDBManager(ref MessagePackage inMes)
        {
            mesQuenue.Enqueue(inMes);
        }

        private static void PushMessageIntoMesDIspacher(ref MessagePackage inMes)
        {
            ClassMessagerDispacher.instance.PushMessageIn(ref inMes);
        }

        public static string dataString(string[] str)
        {
            string daatstring = "";
            DateTime currentTime = DateTime.Now;
            int dataDifference = 0;
            for (int i = 0; i < str.Count(); i++)
            {
                DateTime dt = DateTime.ParseExact(str[i], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
                TimeSpan timeDifference = currentTime.Subtract(dt);
                int seconds = (int)timeDifference.TotalSeconds;
                Console.WriteLine(seconds);
                if (i == 0)
                {
                    dataDifference = seconds;
                    daatstring = str[i];
                }
                else
                {
                    if (dataDifference > seconds) { daatstring = str[i]; }
                }
            }
            return daatstring;

        }

        private static void back_sqlite_thread(object a)
        {
            while(true)
            {
                Thread.Sleep(100);

                if(mesQuenue.TryDequeue(out MessagePackage outMes))
                {
                    switch(outMes.proType)
                    {

                        case ProductType.notifyevent: 
                            {
                                switch(outMes.bytesArry.Array[0])
                                {
                                    case ClassDBcmdDefine.START_WORKSTEPS:
                                        {
                                            LogRecord.Log.mInstance.WriteCommonLog(" db manager recv start work step cmd :" + ClassDBcmdDefine.START_WORKSTEPS.ToString());
                                            DBMessageDataType_NotifyStart2WkorkSteps get = (DBMessageDataType_NotifyStart2WkorkSteps)StructByteConver.BytesToStuct(outMes.bytesArry.Array,  typeof(DBMessageDataType_NotifyStart2WkorkSteps));

                                            string ip =  get.IP[0].ToString() +"."+ get.IP[1].ToString() + "." + get.IP[2].ToString() + "." + get.IP[3].ToString() ;
                                            string time = System.Text.Encoding.ASCII.GetString(get.time);


                                            SQLiteConnection c= ClassDBBusinesses.CreatDB(ip, time);//

                                            ClassDBBusinesses.CreatUnifyInfosWatchBoardTable(ref c);
                                            ClassDBBusinesses.CreatWorkStepsJampEndAllDataTable(ref c);
                                            ClassDBBusinesses.CreatRealDataTable(ref c);


                                            ClassConnectionObj acobj = new ClassConnectionObj();
                                            acobj.connectionKeyStrings = time;
                                            acobj.IP = ip;
                                            acobj.connection = c;
                                            connectionObjdic.TryAdd(acobj.IP, acobj);
                                            LogRecord.Log.mInstance.WriteCommonLog(" db manager recv creat db  with added in dic");

                                        }
                                        break;


                                    case ClassDBcmdDefine.START_WORKSTEPCHANGE_EVENT_CHANGENUTIFYWATCHBAORD:
                                        {
                                            LogRecord.Log.mInstance.WriteCommonLog(" db manager recv change work step with notify db cmd :" + ClassDBcmdDefine.START_WORKSTEPCHANGE_EVENT_CHANGENUTIFYWATCHBAORD.ToString());
                                            DBMessageDataType_NotifyChangeWkorkSteps_updateWatchBoard geto = (DBMessageDataType_NotifyChangeWkorkSteps_updateWatchBoard)StructByteConver.BytesToStuct(outMes.bytesArry.Array, typeof(DBMessageDataType_NotifyChangeWkorkSteps_updateWatchBoard));

                                            string ip = geto.IP[0].ToString() + "." + geto.IP[1].ToString() + "." + geto.IP[2].ToString() + "." + geto.IP[3].ToString();
                                            string time = System.Text.Encoding.ASCII.GetString(geto.time);

                                            bool getc =  connectionObjdic.TryGetValue(ip, out ClassConnectionObj outCon);
                                            if(getc)
                                            {
                                                JsonSerializerSettings set = new JsonSerializerSettings();
                                                string inset_str_struct = Newtonsoft.Json.JsonConvert.SerializeObject(geto , typeof(DBMessageDataType_NotifyChangeWkorkSteps_updateWatchBoard) , set);
                                                SQLiteConnection conec = outCon.connection; //开发到此
                                                ClassDBBusinesses.InsertUnifyInfosBoardTable(ref conec, inset_str_struct);
                                            }else
                                            {

                                            }

                                        }
                                        break;

                                    case ClassDBcmdDefine.START_WORKSTEPCHANGE_EVENT_INSERTALL640POINTDATA:
                                        {
                                            LogRecord.Log.mInstance.WriteCommonLog(" db manager recv change work step with notify db cmd :" + ClassDBcmdDefine.START_WORKSTEPCHANGE_EVENT_INSERTALL640POINTDATA.ToString());


                                        }
                                        break;

                                       default:break;
                                }

                                if(outMes.isNeedReback)
                                {
                                    MessagePackage mes = new MessagePackage();

                                    PushMessageIntoMesDIspacher(ref mes);
                                }

                            }break;

                        case ProductType.request://请求数据
                            {



                            }break;

                        case ProductType.updatapush://上报数据
                            {


                            }break;
                            


                    }


                }



            }


        }


    }



}
